#include "Acceptor.h"
#include "EventLoop.h"
#include "InetAddress.h"
#include "SocketsOps.h"

#include <ctime>
#include <unistd.h>
#include <cstdio>

std::string nowAsString()
{
  char buf[64];
  std::time_t now = std::time(nullptr);
  std::tm tmNow;
  localtime_r(&now, &tmNow);
  std::strftime(buf, sizeof buf, "%Y-%m-%d %H:%M:%S\n", &tmNow);
  return buf;
}

void newConnection(int sockfd, const learnmuduo::InetAddress& peerAddr)
{
  printf("newConnection(): accepted a new connection from %s",
         peerAddr.toHostPort().c_str());

  std::string msg = nowAsString();
  ::write(sockfd, msg.data(), msg.size());
  learnmuduo::sockets::close(sockfd);
}

int main()
{
  printf("main(): pid = %d\n", getpid());

  learnmuduo::InetAddress listenAddr(9981); // Daytime 服务端口
  learnmuduo::EventLoop loop;

  learnmuduo::Acceptor acceptor(&loop, listenAddr);
  acceptor.setNewConnectionCallback(newConnection);
  acceptor.listen();

  loop.loop();
}